"""
插件中心服务
"""
from typing import List, Optional, Dict, Any, Tuple
from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
from src.llm.hiagent_app.models.hiagent_models import Plugin, PluginCategory, ListOption


class PluginService:
    """插件服务类"""
    
    def __init__(self, api_client: Optional[HiAgentAPIClient] = None):
        self.api_client = api_client or HiAgentAPIClient()
    
    def list_available_plugin_categories(self, workspace_id: Optional[str] = None) -> List[PluginCategory]:
        """获取可用的插件分类"""
        body = {}

        if workspace_id:
            body["WorkspaceID"] = workspace_id

        try:
            response = self.api_client.make_request("ListAvailablePluginCategory", body)

            categories = []
            # API返回格式: {"Total": 13, "Items": [{"Key": "AudioVideo", "Value": "音频视频"}, ...]}
            for item in response.get("Items", []):
                categories.append(PluginCategory(
                    category_id=item.get("Key", ""),
                    name=item.get("Value", ""),
                    description=None,  # API不返回描述
                    icon=None,  # API不返回图标
                    plugin_count=None  # API不返回插件数量
                ))

            return categories
        except Exception:
            return []
    
    def list_plugins(
        self,
        workspace_id: Optional[str] = None,
        page: int = 1,
        page_size: int = 20,
        category_id: Optional[str] = None,
        keyword: Optional[str] = None,
        plugin_type: Optional[str] = None,
        is_released: Optional[bool] = None
    ) -> Tuple[List[Plugin], int]:
        """获取插件列表"""
        body = {
            "PageNumber": page,
            "PageSize": page_size
        }

        if workspace_id:
            body["WorkspaceID"] = workspace_id

        # 设置筛选条件
        # API文档：ListPlugin使用meta.PluginFilters
        filter_dict = {}
        if keyword:
            # API文档：字段名是 SearchNameAndDesc，不是 Keyword
            filter_dict["SearchNameAndDesc"] = keyword
        if plugin_type:
            # API文档：字段名是 Types（复数），且是列表类型
            filter_dict["Types"] = [plugin_type]
        if is_released is not None:
            filter_dict["Released"] = is_released
        # 注意：meta.PluginFilters不支持CategoryID/Labels字段，忽略category_id参数

        if filter_dict:
            body["Filter"] = filter_dict

        try:
            response = self.api_client.make_request("ListPlugin", body)

            plugins = []
            for item in response.get("Items", []):
                # 从Labels中提取分类信息（如果存在）
                labels = item.get("Labels", [])
                category_id = labels[0] if labels else None

                plugins.append(Plugin(
                    plugin_id=item.get("ID", ""),
                    name=item.get("Name", ""),
                    description=item.get("Description", ""),
                    category_id=category_id,
                    category_name=None,  # API不直接返回分类名称
                    icon=item.get("Icon"),
                    version=item.get("Version"),
                    author=item.get("Author"),
                    install_count=item.get("Usage"),
                    rating=item.get("Rating"),
                    is_installed=item.get("Configured", False)
                ))

            total = response.get("Total", 0)
            return plugins, total
        except Exception:
            return [], 0
    
    def list_released_plugins(
        self,
        workspace_id: Optional[str] = None,
        page: int = 1,
        page_size: int = 20,
        category_id: Optional[str] = None,
        keyword: Optional[str] = None
    ) -> Tuple[List[Plugin], int]:
        """获取已上架插件列表"""
        body = {
            "Pagination": {
                "PageNumber": page,
                "PageSize": page_size
            }
        }

        if workspace_id:
            body["WorkspaceID"] = workspace_id

        # 设置筛选条件
        # API文档：ListReleasedPlugin使用meta.PluginArchiveBriefFilters
        filter_dict = {}
        if category_id:
            # API文档：字段名是 Labels（列表），不是 CategoryID
            filter_dict["Labels"] = [category_id]
        if keyword:
            # API文档：字段名是 SearchNameAndDesc，不是 Keyword
            filter_dict["SearchNameAndDesc"] = keyword

        if filter_dict:
            body["Filter"] = filter_dict

        # 调试日志
        import logging
        logger = logging.getLogger(__name__)
        logger.info(f"ListReleasedPlugin request body: {body}")

        try:
            response = self.api_client.make_request("ListReleasedPlugin", body)

            plugins = []
            # API返回完整的插件对象，包含所有字段
            for item in response.get("Items", []):
                # 从Labels中提取分类信息（如果存在）
                labels = item.get("Labels", [])
                # Labels是分类标签数组，取第一个作为主分类
                category_id = labels[0] if labels else None

                plugins.append(Plugin(
                    plugin_id=item.get("ID", ""),
                    name=item.get("DisplayName") or item.get("Name", ""),  # 优先使用DisplayName
                    description=item.get("Description", ""),
                    category_id=category_id,
                    category_name=None,  # API不直接返回分类名称，只有Labels数组
                    icon=item.get("Icon"),
                    version=None,  # API未返回版本字段
                    author=None,  # API未返回作者字段
                    install_count=None,  # API未返回使用次数
                    rating=None,  # API未返回评分
                    is_installed=item.get("configured", False) or item.get("TenantConfigured", False)  # 检查是否已配置
                ))

            total = response.get("Total", 0)
            return plugins, total
        except Exception:
            return [], 0
    
    def get_plugin_detail(self, plugin_id: str, workspace_id: Optional[str] = None) -> Optional[Plugin]:
        """获取插件详情"""
        body = {
            "ID": plugin_id
        }
        
        if workspace_id:
            body["WorkspaceID"] = workspace_id
        
        try:
            response = self.api_client.make_request("GetPlugin", body)
            
            item = response
            if not item:
                return None
            
            return Plugin(
                plugin_id=item.get("ID", ""),
                name=item.get("Name", ""),
                description=item.get("Description", ""),
                category_id=item.get("CategoryID"),
                category_name=item.get("CategoryName"),
                icon=item.get("Icon"),
                version=item.get("Version"),
                author=item.get("Author"),
                install_count=item.get("Usage"),
                rating=item.get("Rating"),
                is_installed=item.get("Configured", False)
            )
        except Exception:
            return None
    
    def get_released_plugin_detail(self, plugin_id: str, workspace_id: Optional[str] = None) -> Optional[Plugin]:
        """获取已上架插件详情"""
        body = {
            "ID": plugin_id
        }

        if workspace_id:
            body["WorkspaceID"] = workspace_id

        try:
            response = self.api_client.make_request("GetReleasedPlugin", body)

            item = response
            if not item:
                return None

            # 从Labels中提取分类信息（如果存在）
            labels = item.get("Labels", [])
            category_id = labels[0] if labels else None

            return Plugin(
                plugin_id=item.get("ID", ""),
                name=item.get("DisplayName") or item.get("Name", ""),  # 优先使用DisplayName
                description=item.get("Description", ""),
                category_id=category_id,
                category_name=None,  # API不直接返回分类名称，只有Labels数组
                icon=item.get("Icon"),
                version=None,  # API未返回版本字段
                author=None,  # API未返回作者字段
                install_count=None,  # API未返回使用次数
                rating=None,  # API未返回评分
                is_installed=item.get("configured", False) or item.get("TenantConfigured", False)  # 检查是否已配置
            )
        except Exception:
            return None
    
    def favorite_plugin(self, plugin_id: str, workspace_id: Optional[str] = None) -> bool:
        """收藏插件"""
        body = {
            "ID": plugin_id
        }
        
        if workspace_id:
            body["WorkspaceID"] = workspace_id
        
        try:
            self.api_client.make_request("FavoritePlugin", body)
            return True
        except Exception:
            return False
    
    def unfavorite_plugin(self, plugin_id: str, workspace_id: Optional[str] = None) -> bool:
        """取消收藏插件"""
        body = {
            "ID": plugin_id
        }
        
        if workspace_id:
            body["WorkspaceID"] = workspace_id
        
        try:
            self.api_client.make_request("UnfavoritePlugin", body)
            return True
        except Exception:
            return False
    
    def save_plugin_config(self, plugin_id: str, config: Dict[str, Any], workspace_id: Optional[str] = None) -> bool:
        """保存插件配置（授权）"""
        body = {
            "PluginID": plugin_id,
            "Config": config
        }
        
        if workspace_id:
            body["WorkspaceID"] = workspace_id
        
        try:
            self.api_client.make_request("SavePluginConfig", body)
            return True
        except Exception:
            return False
    
    def remove_plugin_config(self, plugin_id: str, workspace_id: Optional[str] = None) -> bool:
        """移除插件配置（取消授权）"""
        body = {
            "PluginID": plugin_id
        }
        
        if workspace_id:
            body["WorkspaceID"] = workspace_id
        
        try:
            self.api_client.make_request("RemovePluginConfig", body)
            return True
        except Exception:
            return False
    
    def get_plugin_config(self, plugin_id: str, workspace_id: Optional[str] = None) -> Optional[Dict[str, Any]]:
        """获取插件配置"""
        body = {
            "PluginID": plugin_id
        }
        
        if workspace_id:
            body["WorkspaceID"] = workspace_id
        
        try:
            response = self.api_client.make_request("GetPluginConfig", body)
            return response.get("Config")
        except Exception:
            return None